<?php

require '../vendor/autoload.php';

use Slim\Http\Request;
use Slim\Http\Response;

use QL\QueryList;

// Start PHP session
session_start();

$configuration = [
    'settings' => [
        'displayErrorDetails' => true,
    ],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);

// Fetch DI Container
$container = $app->getContainer();

// 加载配置
$container['config'] = function () {
    return new \DavidePastore\Slim\Config\Config('../config/config.json');
};
$app->add($container['config']);

$app->get('/read/{type}', function (Request $request, Response $response, $args) {
    $type = $args['type'];
    if('url' == $type and $url = $_GET[$type]){
        $ql = QueryList::get($url);
        
        /**
         * 上下页连接
         */
        $data = $ql->use(QL\Ext\AbsoluteUrl::class)->rules([
            'title'=>['h1','text'],
            'prev' => ['a:contains(上一):first','href'],
            'next' => ['a:contains(下一):first','href']
        ])->encoding('UTF-8')->removeHead()
        ->absoluteUrl($url)->query()->getData();
        
        $page = $data[0];

        /**
         * 主要内容
         */
        $data = $ql->rules([
            'text' => ['div,p','html',':text']
        ])->query()->getData(function($item){
            if(strpos($item['text'],'div')!==false){
               unset($item['text']);
            }
            return $item;
        });

        $content = '';
        $clen = 0;
        foreach($data as $item){
            if(!array_key_exists('text',$item)) continue;
            $tlen = strlen(strip_tags($item['text']));
            if($tlen and $tlen > $clen){
                $clen = $tlen;
                $content = $item['text'];
            }
        }
        $page['content'] = $content;

        $response->write(json_encode($page,JSON_UNESCAPED_UNICODE));
    }
    return $response;
});

// Run App
$app->run();